﻿using System;
using System.Web;
using System.Web.Caching;

namespace Repo.DataCaching
{
    public class CurrentlyUpdatingCache
    {
        private const string CurrentlyUpdating = "CurrentlyUpdating";

        private static string GetCurrentlyUpdatingKey(string cacheKey)
        {
            if (cacheKey.IndexOf(CurrentlyUpdating) == -1)
            {
                return CurrentlyUpdating + ";" + cacheKey;
            }
            return cacheKey;
        }

        public static bool IsCurrentlyUpdating(string cacheKey)
        {
            var updatingTimekey = GetCurrentlyUpdatingKey(cacheKey);
            var updatingTime = GetUpdatingTime(updatingTimekey);
            return updatingTime != null;
        }

        public static DateTime? GetUpdatingTime(string cacheKey)
        {
            var updatingTimekey = GetCurrentlyUpdatingKey(cacheKey);
            var updatingTime = HttpRuntime.Cache[updatingTimekey];
            if (updatingTime != null)
            {
                return (DateTime)updatingTime;
            }
            return null;
        }

        public static void SaveUpdatingTime(string cacheKey)
        {
            var expiry = new TimeSpan(365, 0, 0, 0);
            var updatingTimekey = GetCurrentlyUpdatingKey(cacheKey);
            DeleteUpdatingTime(updatingTimekey);
            HttpRuntime.Cache.Add(updatingTimekey, DateTime.Now, null, DateTime.Now.Add(expiry),
                                  Cache.NoSlidingExpiration, CacheItemPriority.High, null);
        }

        public static bool DeleteUpdatingTime(string cacheKey)
        {
            var updatingTimekey = GetCurrentlyUpdatingKey(cacheKey);
            if (HttpRuntime.Cache.Get(updatingTimekey) != null)
            {
                HttpRuntime.Cache.Remove(updatingTimekey);
                return true;
            }
            return false;
        }
    }
}
